<?php
namespace services\ucenter;

use Yii;
use models\ucenter\Users;
use yii\db\Query;

/**
 * 用户管理
 *
 * @author dejin <ldj@hianto2o.com>
 */
class UserService extends \services\Service
{
    public static function save($params, $condition = null){
        $user = $condition ? static::getItem($condition) : new Users();

        if($condition && !$user){
            $conditionStr = is_object($condition)  ? json_encode($condition, JSON_UNESCAPED_UNICODE) : $condition;
            return static::fail($conditionStr  . "未找到！");
        }
        
        $user->load($params, '');
        if(!$user->save()){
            return static::fail($user->getErrorMessage());
        }
        return $user;
    }

    public static function register($params){
        $condition = ['OR'];
        if(isset($params['username'])){
            $condition[] = ['username' => $params['username']];
        }
        if(isset($params['mobile'])){
            $condition[] = ['mobile' => $params['mobile']];
        }
        $user = Users::find()->where($condition)->one();
        return $user;
        //static::save($params);
    }

    public static function listByPage($params){
        return static::toListPage(Users::find(), $params);
    }

    public static function getItem($condition){
        return Users::find()->where($condition)->one();
    }

    public static function getUserByWeixinOpenid($openid){
        $weixinUser = (new Query())->from('{{%ucenter_weixin_users}}')->where(['openid' => $openid])->one();
        if(!$weixinUser || !$weixinUser['user_id']){
            return null;
        }
        return Users::findOne($weixinUser['user_id']); 
    }
}
